package cn.phantom.pooltest;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

@Slf4j(topic = "c.TestTimer")
public class TestTimer {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
//        log.debug("start...");
//        pool.schedule(() -> {
//            try {
//                log.debug("task1");
//                int i = 1 / 0;
//            } catch (Exception e) {
//                log.error("error: ", e);
//            }
//        }, 1, TimeUnit.SECONDS);
        // method1(pool);

        // method2(pool);

        ExecutorService pool = Executors.newFixedThreadPool(1);
        Future<Boolean> task1 = pool.submit(() -> {
            log.debug("task1");
            int i = 1 / 0;
            return true;
        });
        log.debug("result: {}", task1.get());

    }

    private static void method2(ScheduledExecutorService pool) {
        pool.scheduleWithFixedDelay(() -> {
            log.debug("running....");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, 1, 1, TimeUnit.SECONDS); // 从上一次任务结束开始算
    }

    private static void method1(ScheduledExecutorService pool) {
        pool.scheduleAtFixedRate(() -> {
            log.debug("running....");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, 1, 1, TimeUnit.SECONDS);
    }
}
